package com.hulman.oms.util;

import com.hulman.oms.shiro.JwtToken;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;

public class ServletUtil
{
    public static String getCookieValue(HttpServletRequest request, String name)
    {
        Cookie[] cookies = request.getCookies();
        if (cookies != null)
        {
            for (Cookie cookie : cookies)
            {
                if (cookie.getName().equals(name))
                {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

    public static String getUrl(HttpServletRequest request)
    {
        String uri = request.getRequestURI();
        String query = request.getQueryString();
        if (StringUtil.isEmpty(query))
        {
            return uri;
        } else
        {
            return uri + "?" + query;
        }
    }

    public static String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(JwtToken.NAME);
        if (StringUtil.isEmpty(token))
        {
            String cookieToken = ServletUtil.getCookieValue(request, JwtToken.NAME);
            if (!StringUtil.isEmpty(cookieToken))
            {
                token = cookieToken;
            }
        }
        if (StringUtil.isEmpty(token))
        {
            String paramToken = request.getParameter(JwtToken.NAME);
            if (!StringUtil.isEmpty(paramToken))
            {
                token = paramToken;
            }
        }
        return token;
    }
}
